package com.itheima.filter;

import com.alibaba.fastjson2.JSON;
import com.itheima.common.R;
import com.itheima.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器，拦截未登录的请求访问其他资源
 * 检查用户是否已经完成登录
 * 使用过滤器实现
 *
 * @author 51585
 */
//@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    /**
     * 路径匹配器
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    /**
     * 过滤方法
     *
     * @param servletRequest  请求对象
     * @param servletResponse 响应对象
     * @param filterChain     过滤器放行
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的uri
        String requestURI = request.getRequestURI();

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                // 放行登录接口
                "/user/loginByAccount",
                "/user/getCaptchaImg",
                "/user/loginByPhone",
                "/user/getPhoneCode",
                // 放行swagger
                "/v2/**",
                "/swagger-ui.html/**",
                "/swagger-resources/**",
                "/webjars/**",
                // 放行knife4j
                "/doc.html",
                // 放行刷新token接口
                "/refresh",
                // 放行websocket
               "/websocket/**"
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }

        //4、判断登录状态，如果已登录，则直接放行
        String token = request.getHeader("Authorization");
        R<String> stringR = JwtUtil.checkToken(token);
        if (stringR.getCode() != 1) {
            response.setHeader("Content-Type","application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(stringR));
        } else {
            filterChain.doFilter(request, response);
        }
    }


    /**
     * 封装判断本次请求是否需要处理的方法
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls       可放行url
     * @param requestURI 当前请求uri
     * @return 结果
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
